package edu.sandau.app.basic.controller;

import edu.sandau.app.basic.domain.Favorite;
import edu.sandau.app.basic.domain.SysUser;
import edu.sandau.app.basic.domain.DishWithBLOBs;
import edu.sandau.app.basic.golbal.GlobalEnum;
import edu.sandau.app.basic.service.FavoriteService;
import edu.sandau.app.basic.service.SysUserService;
import edu.sandau.app.basic.service.DishService;
import edu.sandau.app.basic.vo.BasicMsg;
import edu.sandau.app.basic.vo.BasicMsgWithData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/favorites")
@Tag(name = "收藏管理", description = "收藏管理接口")
public class FavoriteController {
    
    @Autowired
    private FavoriteService favoriteService;
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private DishService dishService;
    
    // 获取用户的所有收藏
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户的所有收藏")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "userId": 1,
                              "dishId": 1
                            },
                            {
                              "userId": 1,
                              "dishId": 2
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "该用户暂无收藏", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "该用户暂无收藏",
                          "errorCode": "FAVORITE_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "FAVORITE_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<Favorite>> getUserFavorites(@PathVariable Long userId) {
        BasicMsgWithData<List<Favorite>> msg = new BasicMsgWithData<>();
        try {
            List<Favorite> favorites = favoriteService.getUserFavorites(userId);
            if (favorites != null && !favorites.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(favorites);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_NOT_FOUND);
                msg.setErrorMsg("该用户暂无收藏");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                msg.setData(null);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            msg.setData(null);
        }
        return msg;
    }
    
    // 添加收藏
    @PostMapping
    @Operation(summary = "添加收藏")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "收藏成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "收藏成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "已经收藏过", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "已经收藏过该菜品",
                          "errorCode": "FAVORITE_ALREADY_EXISTS"
                        }"""),
                    @ExampleObject(name = "用户不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在",
                          "errorCode": "FAVORITE_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "菜品不存在",
                          "errorCode": "FAVORITE_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "多个验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空; 菜品ID不能为空",
                          "errorCode": "FAVORITE_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "收藏失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "收藏失败: 具体错误信息",
                          "errorCode": "FAVORITE_ADD_FAIL"
                        }""")
                }))
    })
    public BasicMsg addFavorite(@RequestBody Favorite favorite) {
        BasicMsg msg = new BasicMsg();
        try {
            StringBuilder errorMsg = new StringBuilder();
            
            // 验证必需字段
            if (favorite.getUserId() == null) {
                errorMsg.append("用户ID不能为空; ");
            }
            if (favorite.getDishId() == null) {
                errorMsg.append("菜品ID不能为空; ");
            }
            
            // 验证用户存在性
            if (favorite.getUserId() != null) {
                SysUser user = sysUserService.getUserById(favorite.getUserId());
                if (user == null) {
                    errorMsg.append("用户不存在; ");
                }
            }
            
            // 验证菜品存在性
            if (favorite.getDishId() != null) {
                DishWithBLOBs dish = dishService.getDishById(favorite.getDishId());
                if (dish == null) {
                    errorMsg.append("菜品不存在; ");
                }
            }
            
            // 如果有验证错误，返回所有错误
            if (errorMsg.length() > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_ADD_FAIL);
                msg.setErrorMsg(errorMsg.toString().trim().replaceAll("; $", ""));
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 系统字段由服务层设置，不需要客户端传递
            favorite.setFavoriteId(null);
            favorite.setCreateTime(null);
            
            int result = favoriteService.addFavorite(favorite);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("收藏成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else if (result == -1) {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_ALREADY_EXISTS);
                msg.setErrorMsg("已经收藏过该菜品");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_ADD_FAIL);
                msg.setErrorMsg("收藏失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_ADD_FAIL);
            msg.setErrorMsg("收藏失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 取消收藏
    @DeleteMapping("/{id}")
    @Operation(summary = "取消收藏")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "取消收藏成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "取消收藏成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "取消收藏失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "取消收藏失败",
                          "errorCode": "FAVORITE_DELETE_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "取消收藏失败: 具体错误信息",
                          "errorCode": "FAVORITE_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg deleteFavorite(@PathVariable Long id) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = favoriteService.deleteFavorite(id);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("取消收藏成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_DELETE_FAIL);
                msg.setErrorMsg("取消收藏失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_DELETE_FAIL);
            msg.setErrorMsg("取消收藏失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据用户ID和菜品ID取消收藏
    @DeleteMapping("/user/{userId}/dish/{dishId}")
    @Operation(summary = "根据用户ID和菜品ID取消收藏")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "取消收藏成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "取消收藏成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "取消收藏失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "取消收藏失败",
                          "errorCode": "FAVORITE_DELETE_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "取消收藏失败: 具体错误信息",
                          "errorCode": "FAVORITE_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg deleteFavoriteByUserAndDish(@PathVariable Long userId, @PathVariable Long dishId) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = favoriteService.deleteFavoriteByUserAndDish(userId, dishId);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("取消收藏成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_DELETE_FAIL);
                msg.setErrorMsg("取消收藏失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_DELETE_FAIL);
            msg.setErrorMsg("取消收藏失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 检查用户是否收藏了某个菜品
    @GetMapping("/user/{userId}/dish/{dishId}")
    @Operation(summary = "检查用户是否收藏了某个菜品")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "已收藏", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": true
                        }"""),
                    @ExampleObject(name = "未收藏", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": false
                        }""")
                }))
    })
    public BasicMsgWithData<Boolean> checkFavorite(@PathVariable Long userId, @PathVariable Long dishId) {
        BasicMsgWithData<Boolean> msg = new BasicMsgWithData<>();
        try {
            boolean isFavorite = favoriteService.checkFavorite(userId, dishId);
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("查询成功");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            msg.setData(isFavorite);
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 获取菜品的收藏数量
    @GetMapping("/dish/{dishId}/count")
    @Operation(summary = "获取菜品的收藏数量")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": 25
                        }"""),
                    @ExampleObject(name = "暂无收藏", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": 0
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "FAVORITE_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<Long> getDishFavoriteCount(@PathVariable Long dishId) {
        BasicMsgWithData<Long> msg = new BasicMsgWithData<>();
        try {
            long count = favoriteService.getDishFavoriteCount(dishId);
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("查询成功");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            msg.setData(count);
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.FAVORITE_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
}
